package parser;
import ioccontainer.BeanDefinition;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;


public class StAXParser implements Parser {
	
	public List<BeanDefinition> parseBeanDefinitions(String xmlPath) {		
		List<BeanDefinition> beanDefinitionList = new ArrayList<>();
		BeanDefinition curBeanDef = null;
		XMLInputFactory factory = XMLInputFactory.newInstance();
		XMLStreamReader r = null;
		try {					
			r = factory.createXMLStreamReader(new FileInputStream(xmlPath));				
			int event = r.getEventType();
			while (true) {
				switch (event) {
				case XMLStreamConstants.START_ELEMENT:
					if(r.getLocalName().equals("bean")) {						
						curBeanDef = new BeanDefinition();
						beanDefinitionList.add(curBeanDef);
						curBeanDef.addAttribute(r.getAttributeLocalName(0), r.getAttributeValue(0));
						curBeanDef.addAttribute(r.getAttributeLocalName(1), r.getAttributeValue(1));
					}			
					if(r.getLocalName().equals("constructor-arg")) {						
						curBeanDef.addConstructorArg(r.getAttributeLocalName(0), r.getAttributeValue(0));												
					}
					if(r.getLocalName().equals("property")) {						
						curBeanDef.addProperty(r.getAttributeLocalName(0), r.getAttributeValue(0), r.getAttributeLocalName(1), r.getAttributeValue(1));	
					}
					break;
				}
				if (!r.hasNext())
					break;
				event = r.next();
			}
			r.close();
		} catch(XMLStreamException xmlse) {
			xmlse.printStackTrace();
		} catch(FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} 
		return beanDefinitionList;		
	}	
	
}
